import { memo, useEffect, useState, useCallback } from 'react';
import {
  Table,
  Card,
  Space,
  Button,
  Popconfirm,
  Tag,
  Typography,
  Input,
  App,
  Avatar,
  Tooltip,
  Empty,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DeleteOutlined, UserOutlined, ReloadOutlined } from '@ant-design/icons';
import { getCommentListApi, deleteCommentApi } from '@/api/adminApi';
import dayjs from 'dayjs';
import styled from 'styled-components';
import { motion } from 'framer-motion';

const { Title, Text } = Typography;
const { Search } = Input;

// 样式组件
const StyledCard = styled(Card)`
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
`;

const ReviewContainer = styled.div`
  padding: 24px;
`;

const HeaderRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
`;

const AnimatedButton = styled(Button)`
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
`;

interface Comment {
  id: string;
  user_id: string;
  course_id: string;
  content: string;
  parent_id: string | null;
  root_id: string | null;
  created_at: Date | null;
  updated_at: Date | null;
  userInfo: {
    id: string;
    username: string;
    avatar: string;
  };
}

// 评论管理页面
const Review = () => {
  const { message: antdMessage, modal } = App.useApp();
  const [commentList, setCommentList] = useState<Comment[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(100);

  // 获取评论列表
  const fetchCommentList = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getCommentListApi();
      if (res.code === 200) {
        setCommentList(res.data as any);
        antdMessage.success('获取评论列表成功');
      } else {
        antdMessage.error(res.message || '获取评论列表失败');
      }
    } catch (error) {
      console.error('获取评论列表出错:', error);
      antdMessage.error('获取评论列表出错');
    } finally {
      setLoading(false);
    }
  }, [antdMessage]);

  // 初始加载数据
  useEffect(() => {
    fetchCommentList();
  }, [fetchCommentList]);

  // 删除评论
  const handleDelete = async (id: string) => {
    try {
      const res = await deleteCommentApi(id);
      if (res.code === 200) {
        antdMessage.success('删除评论成功');
        setCommentList(commentList.filter((item) => item.id !== id));
      } else {
        antdMessage.error(res.message || '删除评论失败');
      }
    } catch (error) {
      console.error('删除评论出错:', error);
      antdMessage.error('删除评论出错');
    }
  };

  // 查看用户信息
  const showUserInfo = (user: Comment['userInfo']) => {
    modal.info({
      title: '用户信息',
      content: (
        <div style={{ display: 'flex', alignItems: 'center', marginTop: 16 }}>
          <Avatar
            size={64}
            src={user.avatar}
            icon={<UserOutlined />}
            style={{ marginRight: 16 }}
          />
          <div>
            <div>
              <Text strong>用户ID:</Text> {user.id}
            </div>
            <div>
              <Text strong>用户名:</Text> {user.username}
            </div>
          </div>
        </div>
      ),
      okText: '关闭',
      maskClosable: true,
    });
  };

  // 表格列定义
  const columns: ColumnsType<Comment> = [
    {
      title: '用户',
      key: 'user',
      width: 150,
      render: (_, record) => (
        <div
          style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
          onClick={() => showUserInfo(record.userInfo)}
        >
          <Avatar
            src={record.userInfo?.avatar}
            icon={<UserOutlined />}
            size="small"
            style={{ marginRight: 8 }}
          />
          <Tooltip title="点击查看用户详情">
            <Text
              ellipsis
              style={{ maxWidth: 120 }}
            >
              {record.userInfo?.username}
            </Text>
          </Tooltip>
        </div>
      ),
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip
          placement="topLeft"
          title={text}
        >
          <Text
            style={{ width: 300 }}
            ellipsis
          >
            {text}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '评论类型',
      key: 'type',
      width: 120,
      render: (_, record) => (
        <Tag color={record.parent_id ? 'blue' : 'green'}>
          {record.parent_id ? '回复评论' : '原始评论'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      sorter: (a, b) => {
        if (!a.created_at || !b.created_at) return 0;
        return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
      },
      render: (date) => (date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '无'),
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      sorter: (a, b) => {
        if (!a.updated_at || !b.updated_at) return 0;
        return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
      },
      render: (date) => (date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '无'),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="确定删除此评论吗?"
            description="删除后无法恢复，请谨慎操作"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AnimatedButton
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </AnimatedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 过滤数据
  const filteredData = commentList.filter((item) => {
    return (
      item.content.toLowerCase().includes(searchText.toLowerCase()) ||
      item.userInfo.username.toLowerCase().includes(searchText.toLowerCase())
    );
  });

  return (
    <ReviewContainer>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <StyledCard>
          <HeaderRow>
            <Title level={4}>评论管理</Title>
            <Space>
              <Search
                placeholder="搜索评论内容或用户名"
                allowClear
                enterButton
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 250 }}
              />
              <AnimatedButton
                type="primary"
                icon={<ReloadOutlined />}
                onClick={fetchCommentList}
                loading={loading}
              >
                刷新
              </AnimatedButton>
            </Space>
          </HeaderRow>

          <Table
            columns={columns}
            dataSource={filteredData}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: pageSize,
              current: page,
              onChange: (page, pageSize) => {
                setPage(page);
                setPageSize(pageSize);
              },
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条评论`,
            }}
            bordered
            size="middle"
            locale={{
              emptyText: (
                <Empty
                  description="暂无评论数据"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              ),
            }}
            components={{
              body: {
                row: (props) => (
                  <motion.tr
                    {...props}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ duration: 0.3 }}
                    whileHover={{
                      backgroundColor: 'rgba(0, 0, 0, 0.02)',
                      transition: { duration: 0.2 },
                    }}
                  />
                ),
              },
            }}
          />
        </StyledCard>
      </motion.div>
    </ReviewContainer>
  );
};

export default memo(Review);
